# get project root directory
function getptop
{
    local TOPFILE=AndroidManifest.xml
    if [ -n "$PTOP" -a -f "$PTOP/$TOPFILE" ] ; then
        echo $PTOP
    else
        if [ -f $TOPFILE ] ; then
            echo $PWD
        else
            # We redirect cd to /dev/null in case it's aliased to
            # a command that prints something as a side-effect
            # (like pushd)
            local HERE=$PWD
            MM_T=
            while [ \( ! \( -f $TOPFILE \) \) -a \( $PWD != "/" \) ]; do
                cd .. > /dev/null
                MM_T=$PWD
            done
            cd $HERE > /dev/null
            if [ -f "$MM_T/$TOPFILE" ]; then
                echo $MM_T
            fi
        fi
    fi
}

function alog() {

    which adb 2>&1 1>&/dev/null || echo "No adb found in PATH", return

    # devices_number = adb_output_lines - 2
    local DEV_NR=$(adb devices | wc -l)
    let DEV_NR=DEV_NR-2

    # process standard adb options
    local adb_target=""
    if [ $# -lt 1 -a "$DEV_NR" = "1" ];
    then
        adb_target=""
    elif [ \( "$1" = "-d" -o "$1" = "-e" \) -a $DEV_NR -lt 3 ]; then
        adb_target=$1
        shift 1
    elif [ "$1" = "-s" ]; then
        adb_target="$1 $2"
        shift 2
    else
        adb devices
        return
    fi

    local adb_options=${adb_target}
    local TIME_FORMAT="%y-%m-%d_%H-%M-%S"

    local LOG_D=$(getptop)/log

    if [ "$LOG_D" = "/log" ];
    then
        LOG_D=/tmp/.alog
    fi

    if [ \( ! -e $LOG_D \) -o -f $LOG_D ];
    then
        rm -rf $LOG_D
        mkdir $LOG_D
    fi

    local prefix=`find $LOG_D/ -type f -regex ".*\.logcat" | wc -l`
    local logcat_options="-v time $*"
    local log_file=${LOG_D}/${prefix}_$(date +$TIME_FORMAT).logcat

    local adb_filters=$(get_adb_filters)
    echo Dumping the log to $log_file

    if [ "$adb_filters"a = ""a ];
    then
        echo "adb $adb_options logcat $logcat_options | tee $log_file | colordump"
        adb $adb_options logcat $logcat_options | tee $log_file | colordump
    else
        echo "adb $adb_options logcat $logcat_options | tee $log_file | eval /bin/grep $(get_adb_filters) | colordump"
        adb $adb_options logcat $logcat_options | tee $log_file | eval /bin/grep $(get_adb_filters) | colordump
    fi

    #adb $adb_options logcat $filter_options | tee $log_file | eval grep $(get_adb_filters) | colordump

}

# get all "String TAG" defined in project
function get_adb_filters () {

    local TOP=$(getptop)

    if [ a"$TOP" == a ];
    then
        return;
    fi

    local tags=`find $TOP/ -type f -regex ".*\.java" |\
                xargs grep "String TAG" |\
                awk 'BEGIN { FS="=" } { print $2 }' |\
                tr -d "\r" |\
                tr -d '"' |\
                tr -d "\n"`

    local tag=""
    local o=""
    for tag in $tags;
    do
        o="$o -e \" [VDIWEFS]/${tag%;}\""
    done
    echo "$o"
}

function set_adb_filters () {
    export ANDROID_LOG_TAGS=$*
}

function wait_for_file () {
    local tries=10;
    while [ \( ! -f $1 \) -a $tries -gt 0 ];
    do
        echo -n "."
        sleep 1
        tries=$((tries-1))
    done
}

function colordump () {

# \1 Log timestamp
# \2 Log level
# \3 Log tag
# \4 Log content
# 01-07 14:31:19.478 D/TAG   ( 1755): log content
awk ' { match($0, /^(..-.. ..:..:......) ([VDIWEFS])\/([^ ]*)[ \t]*\( *[0-9]*\): (.*)/, a);

            match(a[1], /^(..)-(..) (..):(..):(......)/, time);
            m=time[1];
            d=time[2];
            h=time[3];
            m=time[4];
            s=time[5];
            last_ts = ts
            ts=h*3600 + m*60 + s;
            diff_ts=ts-last_ts

            level=a[2];
            tag=a[3];
            content=a[4];
            sub(/\r$/, "", content);

            if (level == "V") color="\033[0;1;31m"
            else if (level == "D") color="\033[0;1;32m"
            else if (level == "I") color="\033[0;1;33m"
            else if (level == "W") color="\033[0;1;34m"
            else if (level == "E") color="\033[0;1;35m"
            else if (level == "F") color="\033[0;1;36m"
            else if (level == "S") color="\033[0;1;37m"
            printf "[%12s] %s%s  \033[0m<%s>\n", diff_ts, color, content, tag;

        }'
}
